/*
                    Tilesheets Class Implementation
*/
#include "Tilesheets.h"

// Initialise static members
map<string, SDL_Surface*> Tilesheets::Sheets = map<string, SDL_Surface*>();
//****************************************

int Tilesheets::Loadsheet(string strSheet)
{
    string strPath = "data//tilesheets//";
    strPath += strSheet;
    strPath += ".png"; // Assume all spritesheets are in png format

    if (Sheets[strSheet] != NULL)
    {
        SDL_FreeSurface(Sheets[strSheet]);
    }

    Sheets[strSheet] = OptimiseAlphaSurface(IMG_Load(strPath.c_str()));

    if (Sheets[strSheet] == NULL)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

bool Tilesheets::SheetLoaded(string strSheet)
{
    if (Sheets[strSheet] == NULL)
    {
        return false;
    }
    else
    {
        return true;
    }
}

void Tilesheets::Freesheets()
{
    for (map<string, SDL_Surface*>::iterator iter = Sheets.begin(); iter != Sheets.end(); iter++)
    {
        SDL_FreeSurface(iter->second);
    }

    Sheets.clear();
}

int Tilesheets::BlitTile(string strSheet, Point srcPosition, Point dstPosition, SDL_Surface* screen)
{
    if (Sheets[strSheet] == NULL)
    {
        return -1;
    }

    SDL_Rect srcRect, dstRect;

    dstRect.x = static_cast<int>(dstPosition.x);
    dstRect.y = static_cast<int>(dstPosition.y);

    srcRect.x = (int)srcPosition.x;
    srcRect.y = (int)srcPosition.y;
    srcRect.w = TILE_WIDTH;
    srcRect.h = TILE_HEIGHT;

    SDL_BlitSurface(Sheets[strSheet] , &srcRect, screen, &dstRect);

    return 0;
}
